Either (effect)
docs
型
Either<R, L>
Rightが左に来てるの紛らわしいなmrsekut.icon
気持ちはわかるが
constructor
code:ts
const foo = Either.right(42);
条件分岐
code:ts
if (Either.isLeft(foo)) {
console.log(The left value is: ${foo.left});
} else {
console.log(The Right value is: ${foo.right});
}
Either.match
code:ts
const message = Either.match(foo, {
onLeft: (left) => The left value is: ${left},
onRight: (right) => The Right value is: ${right},
});
map
map
code:ts
const rightResult = Either.map(Either.right(1), (n) => n + 1);'
mapLeft
ある
mapBoth
code:ts
const transformedRight = Either.mapBoth(Either.right(1), {
onLeft: (s) => s + "!",
onRight: (n) => n + 1,
});
EitherはEffect<A, E, R>のサブタイプ
なので、Effect関連の関数をEitherに適用できる
https://effect.website/docs/data-types/either/#interop-with-effect
code:ts
const head = <A>(array: ReadonlyArray<A>): Either.Either<A, string> =>
array.length > 0 ? Either.right(array0) : Either.left("empty array");
const fetchData = (): Effect.Effect<string, string> => {
const success = Math.random() > 0.5;
return success
? Effect.succeed("some data")
: Effect.fail("Failed to fetch data");
};
const program = Effect.all([head(1, 2, 3), fetchData()]);
Effect.runPromise(program).then(console.log);
/*
Example Output:
1, 'some data'
*/
Either.zipWith
https://effect.website/docs/data-types/either/#zipwith
Either.all
https://effect.website/docs/data-types/either/#all
code:ts
import { Either } from "effect"
const maybeName: Either.Either<string, string> = Either.right("John")
const maybeAge: Either.Either<number, string> = Either.right(25)
// ┌─── Either<string, number, string>
// ▼
const tuple = Either.all(maybeName, maybeAge)
console.log(tuple)
/*
Output:
{ _id: 'Either', _tag: 'Right', right: 'John', 25 }
*/
// ┌─── Either<{ name: string; age: number; }, string>
// ▼
const struct = Either.all({ name: maybeName, age: maybeAge })
console.log(struct)
/*
Output:
{ _id: 'Either', _tag: 'Right', right: { name: 'John', age: 25 } }
*/
便利やんmrsekut.icon
Either.gen
do記法できる
https://effect.website/docs/data-types/either/#gen
code:ts
const maybeName: Either.Either<string, string> = Either.right("John");
const maybeAge: Either.Either<number, string> = Either.right(25);
const program = Either.gen(function* () {
const name = (yield* maybeName).toUpperCase();
const age = yield* maybeAge;
return { name, age };
});
すごいねmrsekut.icon